import uniCopy from "./uni-copy.js";
export default {
	/* 截取字符串，多余的部分用...代替
	 * 参数：
	 * 		str:需要截取的字符串
	 * 		len:保留长度(中文字符占2) */
	cropString(str = "", len = 0) {
		if (len === 0) return str;
		let strlen = 0;
		let s = "";
		for (let i = 0; i < str.length; i++) {
			if (str.charCodeAt(i) > 128) {
				strlen += 2;
			} else {
				strlen++;
			}
			s += str.charAt(i);
			if (strlen >= len) {
				return s + "...";
			}
		}
		return s;
	},

	/* 随机取数 */
	getRandomNum(startNum, endNum) {
		if (endNum === undefined) {
			return parseInt(startNum * Math.random());
		} else {
			let num = parseInt((endNum - startNum) * Math.random())
			return num + startNum;
		}
	},
	
	/* 返回页面 */
	navigateBack() {
		if(getCurrentPages().length > 1){
			uni.navigateBack({})
		}else{
			uni.switchTab({
				url: "/"
			})
		}
	},

	/* 补齐flex布局中space-betwen或space-around中最后一排的空位
	 * 		参数：
	 * 			dataList : 数据表
	 * 			countEveryLine : 每行排列数量
	 * 		isfillEmptyLine : 在数据正好为整行时是否要返回一整行的空白 */
	fillFlexEnd(dataList = [], countEveryLine = 3, isfillEmptyLine = false) {
		let surplusCount = dataList.length % countEveryLine;
		let emptyLine = isfillEmptyLine ? countEveryLine : 0;
		let spaceCount = surplusCount === 0 ? emptyLine : (countEveryLine - surplusCount);
		return new Array(spaceCount).fill("");
	},

	/* 判断变量是否为空 */
	isEmpty(variable) {
		return variable == undefined || variable == "undefined" || variable == null || variable == "null" || variable == "" ? true : false;
	},

	/* 将微博内容按at和#拆分 */
	splitWeibo(weiboContent = "") {
		let finish = weiboContent;
		let contentList = [];
		finish = finish.replace(/@(\S*?) /g, " @$1 ");
		finish = finish.replace(/#(\S*?)#/g, " #$1# ");
		contentList = finish.split(" ");
		return contentList.map(item => {
			switch (true) {
				case (item == ""):
					return {
						content: "",
							type: "null"
					};
					break;
				case (item.substr(0, 1) == "@"):
					return {
						content: item,
							type: "at"
					};
					break;
				case (item.substr(0, 1) == "#" && item.substr(-1, 1) == "#"):
					return {
						content: item,
							type: "topic"
					};
					break;
				default:
					return {
						content: item,
							type: "default"
					};
			}
		});
	},

	/* 获取GET参数 */
	getParameter(url = "") {
		let parameterList = url.split("?").splice(-1)[0].split("&")
		let parameter = {}
		parameterList.forEach(item => {
			let parameterInfo = item.split("=")
			parameter[parameterInfo[0]] = parameterInfo[1];
		});
		return parameter;
	},

	/* 随机生成UUID */
	createUuid() {
		let d = new Date().getTime();
		let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			let r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	},
	
	/**
	* 1腾讯/高德地图转百度地图经纬度
	*/
	qqMapTransBMap(lng, lat) {
		let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		let x = lng;
		let y = lat;
		let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		let lngs = z * Math.cos(theta) + 0.0065;
		let lats = z * Math.sin(theta) + 0.006;
		return {
			lng: lngs,
			lat: lats
		};
	},
	
	/**
	 * 2百度转腾讯/高德
	 */
	bMapTransqqMap(lng, lat) {
		let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		let x = lng - 0.0065;
		let y = lat - 0.006;
		let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		let lngs = z * Math.cos(theta);
		let lats = z * Math.sin(theta);
		return {
			longitude: lngs,
			latitude: lats
		};
	},
	
	/* 判断字符串是否是JSON格式 */
	isJSON(content) {
		if(typeof content == 'string') {
			try {
				JSON.parse(content);
				return true;
			} catch(e) {
				return false;
			}
		}
	},
	
	/* 讲数据条数单位由'个'改成'万' */
	fixCountToTenK(count = 0) {
		return count >= 10000 ? (count / 10000).toFixed(1) + "万" : count
	},
	
	/* 复制文本内容到剪切板 */
	copyText(content = "" , callback = () => {}) {
		// #ifndef H5
		uni.setClipboardData({
			data: content,
			success: () => {
				uni.showToast({
					title: "已复制"
				})
				callback();
			}
		})
		// #endif
		// #ifdef H5
		uniCopy({
			content,
			success: res => {
				uni.showToast({
					title: "已复制"
				})
				callback();
			},
			error:(e)=>{
				uni.showToast({
					title: e,
					icon: 'none',
					duration:3000,
				})
			}
		});
		// #endif
	},
	
	/* 前往其他页面 */
	routeToPage(path , routeType) {
		switch(routeType) {
			case("inner"):
				uni.navigateTo({
					url: path
				})
				break;
			case("tabbar"):
				uni.switchTab({
					url: path
				})
				break;
		}
	},
	
	/* 换算显示像素单位 */
	conversionPixelUnit(value , toUnit = "rpx") {
		let conversionValue = Number(value);
		let sysInfo = uni.getSystemInfoSync();
		switch(toUnit) {
			case("rpx"):
				conversionValue = 750 / sysInfo.windowWidth * Number(value)
				break;
			case("px"):
				conversionValue = sysInfo.windowWidth / 750 * Number(value)
				break;
		}
		return conversionValue;
	},
	
	/* 获取指定节点的信息 */
	getDomInfo(domTag = "" , _this) {
		let query = uni.createSelectorQuery().in(_this);
		return new Promise(resolve => {
			query.select("#readed-dom").boundingClientRect(data => {
				resolve(data)
			}).exec();
		})
	},
	
	/* 获取touch事件屏幕坐标 */
	getTouchScreen(touchEvent = {}) {
		let returnRes = {}
		let getReturn = attr => {
			switch(true) {
				case(touchEvent[attr][0].hasOwnProperty("screenX")):
					returnRes = {
						screenX: touchEvent[attr][0].screenX,
						screenY: touchEvent[attr][0].screenY
					}
					break;
				case(touchEvent[attr][0].hasOwnProperty("clientX")):
					returnRes = {
						screenX: touchEvent[attr][0].clientX,
						screenY: touchEvent[attr][0].clientY
					}
					break;
			}
		}
		if(touchEvent.touches.length > 0){
			getReturn("touches")
		}else{
			getReturn("changedTouches")
		}
		return returnRes;
	},
	
	/* 通过颜色主题类别转化十六位色值 */
	getColorValueByType(type = "primary") {
		switch(type) {
			case("primary"):
				return "#2979ff";
				break;
			case("error"):
				return "#fa3534";
				break;
			case("warning"):
				return "#f90";
				break;
			case("success"):
				return "#19be6b";
				break;
			default:
				return "#ffffff";
		}
	}
}
